#include "rc4.h"

namespace RSA
{
	enum
	{
		perm_1 = 1,
		perm_2 = 2,
		perm_3 = 4,
		perm_4 = 8,
		perm_5 = 16,
		perm_6 = 32,
		perm_7 = 64,
		perm_8 = 128,
		perm_9 = 256,
		perm_10 = 512,
		perm_11 = 1024,
		perm_12 = 2048,
	};

	void rc4_setup( struct rc4_state *s, const uint8 *key, uint32 length )
	{
		uint32 i, j, k, *m, a;

		s->x = 0;
		s->y = 0;
		m = s->m;

		for( i = 0; i < 256; i++ )
		{
			m[i] = i;
		}

		j = k = 0;

		for( i = 0; i < 256; i++ )
		{
			a = m[i];
			j = (uint8)( j + a + key[k] );
			m[i] = m[j]; m[j] = a;
			if ( ++k >= length )
				k = 0;
		}
	}

	void rc4_crypt( struct rc4_state *s, unsigned char *data, uint32 length )
	{ 
		uint32 i, x, y, *m, a, b;

		x = s->x;
		y = s->y;
		m = s->m;

		for( i = 0; i < length; i++ )
		{
			x = (uint8) ( x + 1 ); a = m[x];
			y = (uint8) ( y + a );
			m[x] = b = m[y];
			m[y] = a;
			data[i] ^= m[(uint8) ( a + b )];
		}

		s->x = x;
		s->y = y;
	}
}